package ducna.android.aoeclip.screen.category.fragment;

import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

import ducna.android.aoeclip.R;
import ducna.android.aoeclip.common.controller.BaseFragment;
import ducna.android.aoeclip.common.model.entity.Article;
import ducna.android.aoeclip.common.utils.Constant;
import ducna.android.aoeclip.screen.category.adapter.ArticleListAdapter;
import ducna.android.aoeclip.screen.category.loader.DataArticleLoader;

/**
 * Created by DUCNA on 11/7/2014.
 */
public class ListArticleFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<ArrayList<Article>>, Constant {
    private ArrayList<Article> dataArticles = new ArrayList<Article>();
    private RecyclerView mRecyclerViewArticles;
    private ArticleListAdapter mArticleListAdapter;

    private String categoryId;
    private int fragmentId;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_article, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mRecyclerViewArticles = (RecyclerView) view.findViewById(R.id.recyclerViewFragmentArticle);
        mArticleListAdapter = new ArticleListAdapter(dataArticles, R.layout.item_list_article, getActivity());
        mRecyclerViewArticles.setAdapter(mArticleListAdapter);
        initData();
    }

    public void initData(){
        initProgressDialog();
        Bundle bundle = getArguments();
        categoryId = bundle.getString(ARGUMENT_CATEGORY_ID);
        fragmentId = bundle.getInt(ARGUMENT_FRAGMENT_ID);

        if (dataArticles.size() == 0){
            LoaderManager loaderManager = getActivity().getSupportLoaderManager();
            loaderManager.destroyLoader(fragmentId);
            loaderManager.initLoader(fragmentId, null, this);

        }
    }
    @Override
    public Loader<ArrayList<Article>> onCreateLoader(int i, Bundle bundle) {
        showProgressDialog();
        return new DataArticleLoader(getActivity(), categoryId);
    }

    @Override
    public void onLoadFinished(Loader<ArrayList<Article>> arrayListLoader, ArrayList<Article> articles) {
        hideProgressDialog();
        dataArticles.clear();
        dataArticles.addAll(articles);

        mArticleListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoaderReset(Loader<ArrayList<Article>> arrayListLoader) {

    }
}
